/*  GStruct: data structure helpers for Java
 *  Copyright (C) 2011 Giulio Franco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package gstruct.sequential;

import gstruct.sequential.DecentLinkedList.LinkedListNode;

import java.util.ListIterator;
import java.util.NoSuchElementException;

/**
 * Iterator for {@link DecentLinkedList} instances.
 * @author Giulio Franco <giulio_franco@msn.com>
 *
 * @param <E>	Type of the items contained in the collection.
 */
public class DecentLinkedListIterator<E> implements ListIterator<E> {

	private final DecentLinkedList<E> list;
	private int nextIndex;
	private LinkedListNode<E> nextNode;
	
	public DecentLinkedListIterator(DecentLinkedList<E> list) {
		this.list = list;
		nextIndex = 0;
		nextNode = list.getFirstNode();
	}
	
	@Override
	public void add(E e) {
		throw new UnsupportedOperationException();
	}

	private void advance() {
		nextNode = nextNode.getNext();
		nextIndex += 1;
	}

	@Override
	public boolean hasNext() {
		return nextNode != null;
	}

	@Override
	public boolean hasPrevious() {
		return nextNode != list.getFirst();
	}

	@Override
	public E next() {
		if (nextNode == null) {
			throw new NoSuchElementException();
		}
		E res = nextNode.getItem();
		advance();
		return res;
	}

	@Override
	public int nextIndex() {
		return nextIndex;
	}

	@Override
	public E previous() {
		retrocede();
		return nextNode.getPrevious().getItem();
	}

	private void retrocede() {		
		if (nextNode == null) {
			nextNode = list.getLastNode();
		} else {
			LinkedListNode<E> n = nextNode.getPrevious();
			if (n == null) {
				throw new NoSuchElementException();
			} else {
				nextNode = n;
			}
		}
		nextIndex -= 1;
	}

	@Override
	public int previousIndex() {
		return nextIndex - 1;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}

	@Override
	public void set(E e) {
		throw new UnsupportedOperationException();
	}

	public LinkedListNode<E> nextNode() {
		return nextNode;
	}
	
	public LinkedListNode<E> previousNode() {
		return nextNode.getPrevious();
	}
}
